import { join } from 'node:path';
import { getNavigationItems } from '../../utils/custom-docs';
import { vi, describe, it, expect, beforeEach } from 'vitest';
import type { ContentCollectionKey } from 'astro:content';
import { mockDocs } from './mocks';

type Badge = {
  text: string;
  color: string;
};

// At the top level, create a variable to hold the mock config
let mockConfig = {
  customDocs: {
    sidebar: [
      {
        label: 'Guides',
        items: [
          { label: 'Example Guide', slug: 'guides/quickstart' },
          { label: 'Random Guide', slug: 'guides/02-random' },
        ],
      },
      {
        label: 'Architecture Records',
        items: [
          { label: 'What is an Architecture Decision Record?', slug: 'architecture-records/architecture-decision-record' },
          { label: 'Event-driven architecture adoption', slug: 'architecture-records/eda-adoption' },
          { label: 'Broker of choice', slug: 'architecture-records/broker-of-choice' },
        ],
      },
      {
        label: 'Auto generated docs',
        autogenerated: { directory: 'auto-generated' },
      },
      {
        label: 'Nested Examples',
        items: [
          { label: 'Root page', slug: 'guides/quickstart' },
          {
            label: 'Nested section',
            items: [
              { label: 'Nested page 1', slug: 'guides/quickstart' },
              { label: 'Nested page 2', slug: 'guides/02-random' },
            ],
          },
        ],
      },
      {
        label: 'Operations & Support',
        badge: {
          text: 'New',
          color: 'green',
        },
        collapsed: false,
        items: [
          { label: 'Runbooks', autogenerated: { directory: 'auto-generated', collapsed: false } },
          {
            label: 'Nested Example',
            items: [
              { label: 'Nested Example 1', autogenerated: { directory: 'auto-generated', collapsed: false } },
              {
                label: 'Nested Example 2',
                items: [{ label: 'Nested Example 2.1', autogenerated: { directory: 'auto-generated', collapsed: false } }],
              },
            ],
          },
        ],
      },
    ],
  },
};

vi.mock('@config', () => ({
  default: {
    get customDocs() {
      return mockConfig.customDocs;
    },
  },
}));

const pathToTestCatalog = join(__dirname, 'fake-catalog');

// Mock fs module
vi.mock('node:fs', () => ({
  default: {
    readdirSync: vi.fn((path) => {
      // Mock different directory structures based on the path
      if (path.includes('nested-docs')) {
        return ['getting-started', 'advanced.mdx'];
      }
      if (path.includes('nested-docs/getting-started')) {
        return ['01-intro.mdx', '02-setup.mdx'];
      }
      // Default behavior for other directories
      return ['01-introduction.mdx', '02-hello-world.mdx'];
    }),
    statSync: vi.fn((path) => ({
      isDirectory: () => path.includes('getting-started'),
    })),
    readFileSync: vi.fn((path) => {
      // Return different frontmatter based on the file path
      if (path.includes('getting-started/01-intro')) {
        return '---\ntitle: Introduction to Getting Started\n---\nContent';
      }
      if (path.includes('getting-started/02-setup')) {
        return '---\ntitle: Setup Guide\n---\nContent';
      }
      if (path.includes('advanced.mdx')) {
        return '---\ntitle: Advanced Topics\n---\nContent';
      }
      // Default frontmatter for other files
      if (path.includes('01-introduction')) {
        return '---\ntitle: Introduction\n---\nContent';
      }
      return '---\ntitle: Hello World\n---\nContent';
    }),
  },
}));

vi.mock('astro:content', async (importOriginal) => {
  return {
    ...(await importOriginal<typeof import('astro:content')>()),
    getEntry: (key: ContentCollectionKey, id: string) => {
      // Add mock entries for nested directory structure
      const nestedMockDocs = [
        ...mockDocs,
        {
          id: 'docs/nested-docs/getting-started/01-intro',
          data: { title: 'Introduction to Getting Started', slug: '/nested-docs/getting-started/01-intro' },
        },
        {
          id: 'docs/nested-docs/getting-started/02-setup',
          data: { title: 'Setup Guide', slug: '/nested-docs/getting-started/02-setup' },
        },
        {
          id: 'docs/nested-docs/advanced',
          data: { title: 'Advanced Topics', slug: '/nested-docs/advanced' },
        },
      ];
      return Promise.resolve(nestedMockDocs.find((doc) => doc.id === id));
    },
  };
});

describe('Custom Docs', () => {
  beforeEach(() => {
    process.env.PROJECT_DIR = pathToTestCatalog;
    vi.clearAllMocks();
    // Reset mock config to original state
    mockConfig = {
      customDocs: {
        sidebar: [
          {
            label: 'Guides',
            items: [
              { label: 'Example Guide', slug: 'guides/quickstart' },
              { label: 'Random Guide', slug: 'guides/02-random' },
            ],
          },
          {
            label: 'Architecture Records',
            items: [
              { label: 'What is an Architecture Decision Record?', slug: 'architecture-records/architecture-decision-record' },
              { label: 'Event-driven architecture adoption', slug: 'architecture-records/eda-adoption' },
              { label: 'Broker of choice', slug: 'architecture-records/broker-of-choice' },
            ],
          },
          {
            label: 'Auto generated docs',
            autogenerated: { directory: 'auto-generated' },
          },
          {
            label: 'Nested Examples',
            items: [
              { label: 'Root page', slug: 'guides/quickstart' },
              {
                label: 'Nested section',
                items: [
                  { label: 'Nested page 1', slug: 'guides/quickstart' },
                  { label: 'Nested page 2', slug: 'guides/02-random' },
                ],
              },
            ],
          },
          {
            label: 'Operations & Support',
            badge: {
              text: 'New',
              color: 'green',
            },
            collapsed: false,
            items: [
              { label: 'Runbooks', autogenerated: { directory: 'auto-generated', collapsed: false } },
              {
                label: 'Nested Example',
                items: [
                  { label: 'Nested Example 1', autogenerated: { directory: 'auto-generated', collapsed: false } },
                  {
                    label: 'Nested Example 2',
                    items: [{ label: 'Nested Example 2.1', autogenerated: { directory: 'auto-generated', collapsed: false } }],
                  },
                ],
              },
            ],
          },
        ],
      },
    };
  });

  describe('manually defined items', () => {
    it('returns the sidebar items as they are define', async () => {
      const navigationItems = await getNavigationItems();

      expect(navigationItems).toEqual(
        expect.arrayContaining([
          {
            label: 'Guides',
            items: [
              { label: 'Example Guide', slug: 'guides/quickstart' },
              { label: 'Random Guide', slug: 'guides/02-random' },
            ],
          },
        ])
      );
    });
  });

  describe('nested items', () => {
    it('returns the nested items as they are define', async () => {
      const navigationItems = await getNavigationItems();

      expect(navigationItems).toEqual(
        expect.arrayContaining([
          {
            label: 'Nested Examples',
            items: [
              { label: 'Root page', slug: 'guides/quickstart' },
              {
                label: 'Nested section',
                items: [
                  { label: 'Nested page 1', slug: 'guides/quickstart' },
                  { label: 'Nested page 2', slug: 'guides/02-random' },
                ],
              },
            ],
          },
        ])
      );
    });
  });

  describe('auto generated items', () => {
    it('reads the files in the given directory and returns them as navigation items', async () => {
      process.env.PROJECT_DIR = pathToTestCatalog;

      const navigationItems = await getNavigationItems();

      expect(navigationItems).toEqual(
        expect.arrayContaining([
          {
            label: 'Auto generated docs',
            items: [
              {
                label: 'Introduction',
                slug: '/auto-generated/01-introduction',
              },
              {
                label: 'Hello World',
                slug: '/auto-generated/02-hello-world',
              },
            ],
          },
        ])
      );
    });
  });

  describe('deeply nested autogenerated items', () => {
    it('handles deeply nested auto-generated items correctly', async () => {
      process.env.PROJECT_DIR = pathToTestCatalog;

      const navigationItems = await getNavigationItems();

      expect(navigationItems).toEqual(
        expect.arrayContaining([
          {
            label: 'Operations & Support',
            badge: { text: 'New', color: 'green' },
            collapsed: false,
            items: [
              {
                label: 'Runbooks',
                badge: undefined,
                collapsed: false,
                items: [
                  {
                    label: 'Introduction',
                    slug: '/auto-generated/01-introduction',
                  },
                  {
                    label: 'Hello World',
                    slug: '/auto-generated/02-hello-world',
                  },
                ],
              },
              {
                label: 'Nested Example',
                items: [
                  {
                    label: 'Nested Example 1',
                    badge: undefined,
                    collapsed: false,
                    items: [
                      {
                        label: 'Introduction',
                        slug: '/auto-generated/01-introduction',
                      },
                      {
                        label: 'Hello World',
                        slug: '/auto-generated/02-hello-world',
                      },
                    ],
                  },
                  {
                    label: 'Nested Example 2',
                    items: [
                      {
                        label: 'Nested Example 2.1',
                        badge: undefined,
                        collapsed: false,
                        items: [
                          {
                            label: 'Introduction',
                            slug: '/auto-generated/01-introduction',
                          },
                          {
                            label: 'Hello World',
                            slug: '/auto-generated/02-hello-world',
                          },
                        ],
                      },
                    ],
                  },
                ],
              },
            ],
          },
        ])
      );
    });
  });

  // describe('nested directory structure', () => {
  //   beforeEach(() => {
  //     vi.clearAllMocks();
  //     process.env.PROJECT_DIR = pathToTestCatalog;
  //   });

  //   it('processes nested directories and files correctly', async () => {
  //     // Override the mock config
  //     mockConfig = {
  //       customDocs: {
  //         sidebar: [
  //           {
  //             label: 'Documentation',
  //             autogenerated: { directory: 'nested-docs' },
  //           },
  //         ],
  //       },
  //     };

  //     const navigationItems = await getNavigationItems();

  //     // Find the nested docs section
  //     const nestedDocsSection = navigationItems[0]; // Should be the only item now
  //     expect(nestedDocsSection).toBeDefined();
  //     expect(nestedDocsSection).toEqual({
  //       label: 'Documentation',
  //       badge: undefined,
  //       collapsed: undefined,
  //       items: [
  //         {
  //           label: 'getting-started',
  //           items: [
  //             {
  //               label: 'Introduction to Getting Started',
  //               slug: '/nested-docs/getting-started/01-intro',
  //             },
  //             {
  //               label: 'Setup Guide',
  //               slug: '/nested-docs/getting-started/02-setup',
  //             },
  //           ],
  //           badge: undefined,
  //           collapsed: undefined,
  //         },
  //         {
  //           label: 'Advanced Topics',
  //           slug: '/nested-docs/advanced',
  //         },
  //       ],
  //     });
  //   });

  //   it('maintains proper nesting levels and collapsed state', async () => {
  //     // Override the mock config
  //     mockConfig = {
  //       customDocs: {
  //         sidebar: [
  //           {
  //             label: 'Documentation',
  //             autogenerated: { directory: 'nested-docs', collapsed: true },
  //           },
  //         ],
  //       },
  //     };

  //     const navigationItems = await getNavigationItems();
  //     const nestedDocsSection = navigationItems[0]; // Should be the only item

  //     expect(nestedDocsSection).toEqual({
  //       label: 'Documentation',
  //       collapsed: true,
  //       badge: undefined,
  //       items: [
  //         {
  //           label: 'getting-started',
  //           collapsed: true,
  //           badge: undefined,
  //           items: [
  //             {
  //               label: 'Introduction to Getting Started',
  //               slug: '/nested-docs/getting-started/01-intro',
  //             },
  //             {
  //               label: 'Setup Guide',
  //               slug: '/nested-docs/getting-started/02-setup',
  //             },
  //           ],
  //         },
  //         {
  //           label: 'Advanced Topics',
  //           slug: '/nested-docs/advanced',
  //         },
  //       ],
  //     });
  //   });
  // });
});
